package com.wuhunyu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entities.EduSubject;
import com.wuhunyu.entities.excel.SubjectData;
import com.wuhunyu.listener.EduSubjectListener;
import com.wuhunyu.mapper.EduSubjectMapper;
import com.wuhunyu.entities.pojo.Subject;
import com.wuhunyu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author wuhunyu
 * @since 2021-01-16
 */
@Service("eduSubjectService")
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Resource
    private EduSubjectMapper eduSubjectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new EduSubjectListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            Assert.isRight(false, e.getMessage());
        }
        return CommonResult.success("添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSubjectDetail(String oneSubjectName, String twoSubjectName) {
        // 校验非空
        Assert.isRight(Check.isBlank(oneSubjectName), "一级课程名称不能为空");
        Assert.isRight(Check.isBlank(twoSubjectName), "二级课程名称不能为空");
        // 查询是否存在一级课程
        QueryWrapper<EduSubject> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("title", oneSubjectName);
        // 一级课程不存在，则插入一级课程
        EduSubject parentSubject = eduSubjectMapper.selectOne(queryWrapper1);
        EduSubject subject = new EduSubject();
        if (Check.isBlank(parentSubject)) {
            // 课程名称
            subject.setTitle(oneSubjectName);
            // 一级课程的父级课程id默认为0
            subject.setParentId("0");
            // 课程排序，默认为零
            subject.setSort(0);
            // 执行插入操作
            Assert.isRight(eduSubjectMapper.insert(subject) != 1, "一级课程添加失败");
        }
        // 查询是否存在二级课程
        QueryWrapper<EduSubject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("title", twoSubjectName);
        // 二级课程不存在，则插入
        if (Check.isBlank(eduSubjectMapper.selectOne(queryWrapper2))) {
            // 插入之前需要获取父级课程的id
            String id = null;
            if (Check.isBlank(parentSubject)) {
                id = subject.getId();
            } else {
                id = parentSubject.getId();
            }
            subject = new EduSubject();
            subject.setParentId(id);
            // 课程名称
            subject.setTitle(twoSubjectName);
            // 课程排序，默认为0
            subject.setSort(0);
            // 执行插入操作
            Assert.isRight(eduSubjectMapper.insert(subject) != 1, "二级课程添加失败");
        }
    }

    /**
     * 线性集合转换成tree
     * @param subjects
     * @param parentId
     * @return
     */
    public List<Subject> convertTree(List<Subject> subjects, String parentId) {
        if (Check.isBlank(subjects)) {
            return new ArrayList<Subject>();
        }
        // 父节点
        ArrayList<Subject> parents = new ArrayList<>();
        // 子节点
        ArrayList<Subject> sons = new ArrayList<>();
        // 循环将父节点和子节点分离
        subjects.forEach(subject -> {
            // 父节点
            if (parentId.equals(subject.getParentId())) {
                parents.add(subject);
            } else {
                // 子节点
                sons.add(subject);
            }
        });
        // 递归
        parents.forEach(subject -> {
            List<Subject> subjectList = convertTree(sons, subject.getId());
            subject.setChildren(subjectList);
        });
        return parents;
    }

    @Override
    public CommonResult selectAllSubjects() {
        // 查询所有的课程
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "title", "parent_id");
        // 执行查询操作
        List<EduSubject> eduSubjects = baseMapper.selectList(queryWrapper);
        if (Check.isBlank(eduSubjects)) {
            return CommonResult.success("课程信息为空", null);
        }
        ArrayList<Subject> subjects = new ArrayList<>();
        eduSubjects.forEach(subject -> {
            subjects.add(new Subject(subject.getId(), subject.getTitle(), subject.getParentId()));
        });
        // 调用转换方法，顶级id默认为0
        List<Subject> subjectList = convertTree(subjects, "0");
        if (Check.isBlank(subjectList)) {
            return CommonResult.success("课程信息转换失败", null);
        }
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("subject", subjectList);
        return CommonResult.success("查询课程信息成功", map);
    }

    @Override
    public CommonResult selectSubjectsForSelect() {
        // 执行查询操作
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "title", "parent_id");
        List<EduSubject> eduSubjects = this.list(queryWrapper);
        // 校验结果
        Assert.isRight(Check.isBlank(eduSubjects), "课程分类信息为空");
        // 封装结果
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("subjects", eduSubjects);
        return CommonResult.success("查询课程信息成功", map);
    }
}
